//
//  collectionViewController.swift
//  fsapp
//
//  Created by zguang on 17/8/6.
//  Copyright © 2017年 huangshengjie. All rights reserved.
//

import UIKit
import Alamofire
import SVProgressHUD
class collectionViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
        
        
        let tableview = UITableView()
        let childView = ChildView(type:"fill")
        var moneySort = false
        var timeSort = false
        var countSort = false
        var titleArray = [String]()
        var moneyArray = [String]()
        var timeArray =  [String]()
        var playCout = [String]()
        var likeCount = [String]()
        var commitCount = [String]()
        var starCount = [String]()
        var video_src = [String]()
        var pic_src = [String]()
        var iscollected = [String]()
        var videoID = [String]()
        var header = UIView()
        var isLike = [String]()
        var isCollection = [String]()
    
    lazy var headerView : UIView = {
        let tempview  = UIView()
        tempview.frame = CGRect(x:0,y:0,width:SCREEN_WIDTH,height:getHeight( 128))
        let title = UILabel()
        title.frame = CGRect(x:getWidth(width: 0),y:getHeight(55),width:getWidth(width: 0),height:getHeight(0))
        //  title.frame = CGRect(x:self.getWidth(width: 0),y:self.getHeight(height: 55),width:self.getWidth(width: 0),height:self.getHeight(height: 0))
        
        // title.textAlignment = .center
        title.text = "我的收藏"
        title.font = UIFont.systemFont(ofSize:getHeight(42))
        title.sizeToFit()
        title.center = CGPoint(x:SCREEN_WIDTH/2.0,y:title.center.y)
        
        title.textColor = UIColor.white
        
        let image = UIImageView()
        if(self.title == ""){
            image.image = UIImage(named:"电话")
        }
        image.frame = CGRect(x:getWidth(width: 175),y:getHeight(0),width:getWidth(width: 42),height:getHeight(42))
        title.addSubview(image)
        tempview.addSubview(title)
        tempview.backgroundColor = naviColor
        return tempview
    }()
    
    
    lazy var returnButton:UIButton = {
        let btn = UIImageView()
        //imgV.frame = CGRectMake(WIDTH(23), HEIGHT(62), WIDTH(25), HEIGHT(45));
        
        btn.frame = CGRect(x: getWidth(width: 24), y: CGFloat(getHeight(62)), width: getWidth(width: 25), height: getHeight(45));
        btn.image = UIImage(named:"return")
        let back = UIButton()
        back.frame = CGRect(x: getWidth(width: 0), y: CGFloat(getHeight(0)), width: getWidth(width: 70), height: getHeight(128));
        back.addSubview(btn)
        return back
    }()
   
        
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
        override func viewDidLoad() {
            
            super.viewDidLoad()
            headerView.addSubview(returnButton)
            returnButton.addTarget(self, action: #selector(popback), for: .touchUpInside)
            self.view.addSubview(headerView)
            
            
            //self.view.addSubview(header)
            header.backgroundColor = naviColor
            Alarequest()
            initTV()
            //self.view.addSubview(childView.headerView)
            childView.moneySort.addTarget(self, action: #selector(moneyClick(_:)), for: .touchUpInside)
            childView.countSort.addTarget(self, action: #selector(countClick(_:)), for: .touchUpInside)
            childView.timeSort.addTarget(self, action: #selector(timeClick(_:)), for: .touchUpInside)
            // Do any additional setup after loading the view.
        }
        
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        //MARK: - TableviewDelegate
        func initTV (){
            
            tableview.frame = CGRect(x:0,y:height(128),width:SCREEN_WIDTH,height:SCREEN_HEIGHT)
            tableview.delegate = self
            tableview.dataSource = self
            // tableview.backgroundColor = UIColor.blue
            // view.backgroundColor = UIColor.red
            // self.view.addSubview(tableview)
            self.view.addSubview(tableview)
            
        }
        
        //MARK: -  Basic Func
        
    //MARK: -  Basic Func
    
    func moneyClick(_ btn:UIButton){
        
        
        
        
        if !btn.isSelected{
            //            let anim = CABasicAnimation(keyPath: "transform.rotation")
            //            anim.toValue = 1 * M_PI/2
            //            anim.duration = 0.2
            //            anim.repeatCount = 0
            //          //  btn.imageView?.stopAnimating()
            //
            //            anim.isRemovedOnCompletion = true
            //            btn.imageView?.layer.add(anim, forKey: nil)
            //  btn.imageView?.removeAllAnimations()
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: CGFloat(M_PI)))!
            }
            
            var newplay = [Int]()
            for i in moneyArray{
                let nn = i.components(separatedBy: ".")
                newplay.append(Int(nn[0])!)
            }
            playCountbubbleSort(arr: &newplay)
            self.tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }else{
            //            let anim = CABasicAnimation(keyPath: "transform.rotation")
            //            anim.toValue =  -(1 * M_PI)/2
            //            anim.duration = 0.2
            //            anim.repeatCount = 0
            //            anim.isRemovedOnCompletion = true
            //            btn.imageView?.layer.add(anim, forKey: nil)
            //
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: -CGFloat(M_PI)))!
            }
            
            videoID.reverse()
            titleArray.reverse()
            timeArray.reverse()
            moneyArray.reverse()
            playCout.reverse()
            likeCount.reverse()
            commitCount.reverse()
            starCount.reverse()
            pic_src.reverse()
            video_src.reverse()
            tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }
        
    }
    func timeClick(_ btn:UIButton){
        //var ll = "5:20"
        
        
        /// print(Int(newll[0]))
        if !btn.isSelected{
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: CGFloat(M_PI)))!
            }
            var newplay = [Int]()
            for i in timeArray{
                let newll = i.components(separatedBy: ":")
                newplay.append(Int(newll[0])!)
            }
            playCountbubbleSort(arr: &newplay)
            self.tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }else{
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: -CGFloat(M_PI)))!
            }
            videoID.reverse()
            titleArray.reverse()
            timeArray.reverse()
            moneyArray.reverse()
            playCout.reverse()
            likeCount.reverse()
            commitCount.reverse()
            starCount.reverse()
            pic_src.reverse()
            video_src.reverse()
            tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }
    }
    func countClick(_ btn:UIButton){
        if !btn.isSelected{
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: CGFloat(M_PI)))!
            }
            var newplay = [Int]()
            for i in playCout{
                newplay.append(Int(i)!)
            }
            playCountbubbleSort(arr: &newplay)
            self.tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }else{
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: -CGFloat(M_PI)))!
            }
            videoID.reverse()
            titleArray.reverse()
            timeArray.reverse()
            moneyArray.reverse()
            playCout.reverse()
            likeCount.reverse()
            commitCount.reverse()
            starCount.reverse()
            pic_src.reverse()
            video_src.reverse()
            tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }
    }
    
        //冒泡排序
        func playCountbubbleSort( arr: inout [Int]) -> [Int] {
            for i in 0 ..< arr.count {
                for j in 0 ..< arr.count - 1 - i {
                    if arr[j] > arr[j + 1] {
                        let temp = arr[j]
                        arr[j] = arr[j + 1]
                        arr[j + 1] = temp
                        let temp2 = videoID[j]
                        videoID[j] = videoID[j+1]
                        videoID[j+1] = temp2
                        
                        let temp3 = titleArray[j]
                        titleArray[j] = titleArray[j+1]
                        titleArray[j+1] = temp3
                        
                        let temp4 = timeArray[j]
                        timeArray[j] = timeArray[j+1]
                        timeArray[j+1] = temp4
                        
                        let temp5 = moneyArray[j]
                        moneyArray[j] = moneyArray[j+1]
                        moneyArray[j+1] = temp5
                        
                        let temp6 = playCout[j]
                        playCout[j] = playCout[j+1]
                        playCout[j+1] = temp6
                        
                        let temp7 = likeCount[j]
                        likeCount[j] = likeCount[j+1]
                        likeCount[j+1] = temp7
                        
                        let temp8 = commitCount[j]
                        commitCount[j] = commitCount[j+1]
                        commitCount[j+1] = temp8
                        
                        let temp9 = starCount[j]
                        starCount[j] = starCount[j+1]
                        starCount[j+1] = temp9
                        
                        let temp10 = pic_src[j]
                        pic_src[j] = pic_src[j+1]
                        pic_src[j+1] = temp10
                        
                        let temp11 = video_src[j]
                        video_src[j] = video_src[j+1]
                        video_src[j+1] = temp11
                    }
                    
                }
            }
            return arr
        }
    
    
    func popback(){
         self.dismiss(animated: false, completion: nil)
      self.navigationController?.popViewController(animated: true)
    }
        
        
        // MARK: - tableview 代理
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return titleArray.count
        }
        
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            
            return getHeight(483)
            
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = FillLearnTableViewCell(style:.default,reuseIdentifier:"cell")
            cell.title.text = titleArray[indexPath.row]
            cell.timeSpan.text = timeArray[indexPath.row]
            cell.money.text = "¥ " + moneyArray[indexPath.row]
            cell.playButton.tag = indexPath.row
            cell.playButton.addTarget(self, action: #selector(touchplaycell(_:)), for: .touchUpInside)
            
           cell.backImage.imageFromURL(self.pic_src[indexPath.row], placeholder: #imageLiteral(resourceName: "test"))
            
            //cell.backImage.image = #imageLiteral(resourceName: "test")
            cell.videoCount.setTitle(playCout[indexPath.row
                ], for: .normal)
            cell.likeCount.setTitle(likeCount[indexPath.row], for: .normal)
            cell.coommitCount.setTitle(commitCount[indexPath.row], for: .normal)
            cell.starCount.setTitle(starCount[indexPath.row], for: .normal)
            cell.starCount.isSelected = true
            if isCollection[indexPath.row] == "1"{
                cell.starCount.isSelected = true
            }
            if isLike[indexPath.row] == "1" {
                cell.likeCount.isSelected = true
            }
            
            
            
            
            return cell
            
            
        }
        
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
           
            self.navigationController?.navigationBar.tintColor = UIColor.white
            self.navigationController?.navigationBar.barTintColor = naviColor
            self.navigationController?.navigationBar.isHidden = false
            self.navigationController?.navigationBar.tintColor = UIColor.white
            self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"",style:.plain,target:nil,action:nil)
            self.present(VideoDetailViewController(self.video_src[indexPath.row],self.videoID[indexPath.row]), animated: true, completion: nil)
            //self.navigationController?.pushViewController(VideoDetailViewController(self.video_src[indexPath.row],self.videoID[indexPath.row]), animated: true)
            
            
        }
        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return childView.headerView.frame.height
        }
    func touchplaycell(_ btn:UIButton){
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"",style:.plain,target:nil,action:nil)
        self.navigationController?.pushViewController(VideoDetailViewController(self.video_src[btn.tag],self.videoID[btn.tag]), animated: true)
        
    }
        
        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            //let view = UIView(frame: view.frame)
            //view.addSubview(sliderGallery.view)
            return childView.headerView
        }
        
        //MARK: - 网络请求
        
        func Alarequest(){
            let url = "http://dahan-api.heiyou.net/index.php/home/user/ViewCollections"
            self.loadCookies()
            Alamofire.request( url, method: .post).responseJSON{ response in
                if let al = response.response{
                    
                }else{
                    SVProgressHUD.showError(withStatus: "网络连接失败")
                }
                
                if let JSON2 = response.result.value {
                    let js = JSON(JSON2)
                    print(js)
                    if js["status"] == 200{
                        var newtitleArray = [String]()
                        var newmoneyArray = [String]()
                        var newtimeArray =  [String]()
                        var newplayCout = [String]()
                        var newlikeCount = [String]()
                        var newcommitCount = [String]()
                        var newstarCount = [String]()
                        var newvideo_src = [String]()
                        var newpic_src = [String]()
                        var newID = [String]()
                        var newlike = [String]()
                        var newcollect = [String]()
                        
                        if js["length"].int != 0{
                            for i in 0...js["length"].int!-1{
                                newtitleArray.append(js["result"][i]["name"].string!)
                                newmoneyArray.append(js["result"][i]["price"].string!)
                                if let arr = js["result"][i]["duration"].string{
                                    newtimeArray.append(arr)
                                }else{
                                    newtimeArray.append("0")
                                }
                                newpic_src.append(js["result"][i]["pic_src"].string!)
                                newvideo_src.append(js["result"][i]["video_src"].string!)
                                newplayCout.append(js["result"][i]["play"].string!)
                                newlikeCount.append(js["result"][i]["good"].string!)
                                newcommitCount.append(js["result"][i]["comment"].string!)
                                if let arr = js["result"][i]["nums"].string{
                                    newstarCount.append(arr)}
                                else{
                                    newstarCount.append("0")
                                }
                                newID.append(js["result"][i]["id"].string!)
                                if let like =  js["result"][i]["actionPoint"].string{
                                    newlike.append(like)
                                    
                                }else{
                                    newlike.append("")
                                }
                                if let collected =  js["result"][i]["actionCollection"].string{
                                    newcollect.append(collected)
                                }else{
                                    newcollect.append("")
                                }

                            }
                            self.titleArray = newtitleArray
                            self.timeArray = newtimeArray
                            self.moneyArray = newmoneyArray
                            self.pic_src = newpic_src
                            self.video_src = newvideo_src
                            self.commitCount = newcommitCount
                            self.likeCount = newlikeCount
                            self.commitCount = newcommitCount
                            self.starCount = newstarCount
                            self.playCout = newplayCout
                            self.videoID = newID
                            self.isLike = newlike
                            self.isCollection = newcollect
                            self.tableview.reloadData()
                            
                        }
                    }else{
                        SVProgressHUD.dismiss(withDelay: 1)
                        SVProgressHUD.showError(withStatus: js["msg"].string!)
                    }
                    
                    
                }
                
            }
        }
        
        
    func loadCookies(){
    
    }
        
        
    
        
        
        
        /*
         // MARK: - Navigation
         
         // In a storyboard-based application, you will often want to do a little preparation before navigation
         override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         // Get the new view controller using segue.destinationViewController.
         // Pass the selected object to the new view controller.
         }
         */
        
}
